package com.liveinstars.gateway.business.service.impl;

import com.liveinstars.api.dto.User;
import com.liveinstars.api.facade.UserAccountApi;
import com.liveinstars.gateway.business.service.JWTAuthService;
import com.onepiece.cache.service.CacheService;
import com.onepiece.shipelves.common.utils.JsonWebTokenUtil;
import com.onepiece.shipelves.common.utils.JwtAccount;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author: ting
 * @date: 2019-07-31
 */
@Service("jwtAuthService")
public class JWTAuthServiceImpl implements JWTAuthService {

    private static final Logger logger = LoggerFactory.getLogger(JWTAuthServiceImpl.class);

    @Autowired
    CacheService cache;

    @Autowired
    UserAccountApi accountApi;


    @Override
    public String getTokenByUser(User user) {
//        try {
////            if (! checkUser(user)) {
////                throw new Exception();
////            }
////            String token = JwtUtils.generateToken(user, RSAUtil.FORWARD_PRIVATE_KEY, 1);
////            return token;
////        } catch (Exception e) {
////
////        }
        return null;
    }

    @Override
    public Boolean validateToken(String token, String userId) {

        JwtAccount jwtAccount = null;
        try{
            jwtAccount = JsonWebTokenUtil.parseJwt(token,JsonWebTokenUtil.SECRET_KEY);
            if(jwtAccount.getAppId().equals(userId)){
                return true;
            }else {
                return false;
            }
        } catch(SignatureException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e){
            // 令牌错误
            logger.error("errJwt" +  token);
        } catch(ExpiredJwtException e){
            // 令牌过期
            logger.error("expiredJwt" + token);

        } catch(Exception e){
            logger.error("errJwt" + token);
        }
        if(null == jwtAccount){
            logger.error("errJwt" + token);
        }
        return false;

    }
//    public User decrypt(String msg) {
//        String decode = RSAUtil.decode(msg, RSAUtil.FORWARD_PRIVATE_KEY);
//        User user = JSON.parseObject(msg, User.class);
//        return user;
//    }
//
//    public boolean checkUser(User user) {
//        User sign = decrypt(user.getSign());
//        if (user.getAccount() == "8btc-app" && user.getPassword().equals("123456")) {
//            return true;
//        }
//        return false;
//    }
}
